﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MyTRCP.Common.Services;
using System.Runtime.InteropServices;
using System.Text;

namespace MyTRCP.Client
{
    public class Program
    {
        #region 激活关闭窗口事件
        public delegate bool ControlCtrlDelegate(int CtrlType);
        [DllImport("kernel32.dll")]
        private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerAppClose, bool Add);
        private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerAppClose);

        private static IHost? _host;
        /// <summary>
        /// 关闭窗口时的事件
        /// </summary>
        /// <param name="CtrlType"></param>
        /// <returns></returns>
        static bool HandlerAppClose(int CtrlType)
        {
            _host?.StopAsync().GetAwaiter().GetResult();
            return false;
        }

        #endregion

        [STAThread]
        public static void Main(string[] args)
        {
            bool bRet = SetConsoleCtrlHandler(cancelHandler, true);
            ThreadPool.SetMinThreads(30, 30);
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var builder = Host.CreateApplicationBuilder(args);
            builder.Services.AddSingleton<IConfigService, ClientConfigService>();
            builder.Services.AddSingleton<MyProtocolClientSideService>();
            builder.Services.AddSingleton<DevCtrlLinkService>();
            builder.Services.AddSingleton<DevAudioLinkService>();
            builder.Services.AddSingleton<AudioConvertService>();
            builder.Services.AddSingleton<AudioPlayService>();
            builder.Services.AddSingleton<MicRecordService>();
            builder.Services.AddSingleton<AudioAvgLouldnessComputeService>();
            builder.Services.AddSingleton<AudioRecordService>();
            builder.Services.AddSingleton<DevCmdService>();
            builder.Services.AddSingleton<RemoteAudioRouteService>();
            builder.Services.AddSingleton<MicAudioRouteService>();
            builder.Services.AddSingleton<MyAudioRouteService>();
            builder.Services.AddHostedService<MyWpfStarter>();

            _host = builder.Build();
            _host.Run();
        }
    }
}
